<?php

namespace app\admin\controller\timetable;

use app\common\controller\Backend;
use think\addons\Service;
use think\Exception;

/**
 * 系统配置
 *
 * @icon fa fa-gears
 */
class Config extends Base
{
    protected $model = null;
    protected $noNeedRight = ['*'];

    /**
     * 查看
     */
    public function index()
    {
        $info = get_addon_info('timetable');
        $config = get_addon_fullconfig('timetable');
        if (!$info) {
            $this->error(__('No Results were found'));
        }
        if ($this->request->isPost()) {
            $params = $this->request->post("row/a", [], 'trim');
            if ($params) {
                foreach ($config as $k => &$v) {
                    if (isset($params[$v['name']])) {
                        if ($v['type'] == 'array') {
                            $params[$v['name']] = is_array($params[$v['name']]) ? $params[$v['name']] : (array)json_decode($params[$v['name']], true);
                            $value = $params[$v['name']];
                        } else {
                            $value = is_array($params[$v['name']]) ? implode(',', $params[$v['name']]) : $params[$v['name']];
                        }
                        $v['value'] = $value;
                    }
                }
                try {
                    //更新配置文件
                    set_addon_fullconfig('timetable', $config);
                    Service::refresh();
                    $this->success();
                } catch (Exception $e) {
                    $this->error(__($e->getMessage()));
                }
            }
            $this->error(__('Parameter %s can not be empty', ''));
        }
        $this->view->assign("addon", ['config' => $config]);
        return $this->view->fetch();
    }
}